package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableTieCardAmountRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;

public class TagTieCardAmountRecord {
    public long uid;
    public int tiecard_increase_success_time;
    public int tiecard_increase_fail_time;
    public int tiecard_amount_expired_time;

    public static final String SEPARATOR = "#";

    public TagTieCardAmountRecord(
            long uid,
            int tiecard_increase_success_time,
            int tiecard_increase_fail_time,
            int tiecard_amount_expired_time) {
        this.uid = uid;
        this.tiecard_increase_success_time = tiecard_increase_success_time;
        this.tiecard_increase_fail_time = tiecard_increase_fail_time;
        this.tiecard_amount_expired_time = tiecard_amount_expired_time;
    }

    public static TagTieCardAmountRecord init(long uid) {
        return new TagTieCardAmountRecord(uid, 0, 0, 0);
    }

    public static Logger LOG = LoggerFactory.getLogger(TagTieCardAmountRecord.class);

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableTieCardAmountRecord.QUERYSQL);
        DataStream<Tuple2<Boolean, TableTieCardAmountRecord>> inputStream =
                tableEnv.toRetractStream(tableRes, TableTieCardAmountRecord.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableTieCardAmountRecord>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableTieCardAmountRecord> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagTieCardAmountRecord-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableTieCardAmountRecord>, Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableTieCardAmountRecord> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableTieCardAmountRecord>, String>() {
                                    ValueState<TagTieCardAmountRecord> tagTieCardAmountRecordVstate;
                                    MapState<String, String> tagTieCardAmountRecordMstate;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tagTieCardAmountRecordVstate =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagTieCardAmountRecord>(
                                                                        "TagTieCardAmountRecordVstate",
                                                                        TagTieCardAmountRecord
                                                                                .class));
                                        tagTieCardAmountRecordMstate =
                                                getRuntimeContext()
                                                        .getMapState(
                                                                new MapStateDescriptor<
                                                                        String, String>(
                                                                        "TagTieCardAmountRecordMstate",
                                                                        String.class,
                                                                        String.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableTieCardAmountRecord> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int status = value.f1.getStatus();
                                        String increase_req_id = value.f1.getIncrease_req_id();
                                        int increase_time =
                                                (int)
                                                        (value.f1.getIncrease_time().getTime()
                                                                / 1000);
                                        int expired_time =
                                                (int) (value.f1.getExpire_time().getTime() / 1000);

                                        TagTieCardAmountRecord tmpState =
                                                tagTieCardAmountRecordVstate.value();
                                        TagTieCardAmountRecord curState =
                                                tmpState == null
                                                        ? TagTieCardAmountRecord.init(uid)
                                                        : tmpState;

                                        int tmp_incre_fail_time = 0;
                                        int tmp_incre_sucs_time = 0;
                                        int tmp_incre_exp_time = 0;

                                        String mStateVal =
                                                status
                                                        + SEPARATOR
                                                        + increase_time
                                                        + SEPARATOR
                                                        + expired_time;

                                        tagTieCardAmountRecordMstate.put(
                                                increase_req_id, mStateVal);
                                        Iterator<String> iterator =
                                                tagTieCardAmountRecordMstate.values().iterator();

                                        while (iterator.hasNext()) {
                                            String input = iterator.next();
                                            String[] splits = input.split(SEPARATOR);
                                            if (splits.length == 3) {
                                                int state = Integer.parseInt(splits[0]);
                                                int incre_time = Integer.parseInt(splits[1]);
                                                int expire_time = Integer.parseInt(splits[2]);

                                                switch (state) {
                                                    case 0:
                                                        if (tmp_incre_fail_time < incre_time) {
                                                            tmp_incre_fail_time = incre_time;
                                                        }
                                                        break;
                                                    case 2:
                                                        // 区分计算
                                                        if (tmp_incre_sucs_time < incre_time) {
                                                            tmp_incre_sucs_time = incre_time;
                                                        }
                                                        if (tmp_incre_exp_time < expire_time) {
                                                            tmp_incre_exp_time = expire_time;
                                                        }
                                                        break;
                                                    case 5:
                                                        if (tmp_incre_exp_time < expire_time) {
                                                            tmp_incre_exp_time = expire_time;
                                                        }
                                                        break;
                                                    default:
                                                        LOG.error(
                                                                "uid: "
                                                                        + uid
                                                                        + " status: "
                                                                        + status
                                                                        + " state: "
                                                                        + state
                                                                        + " not support now");
                                                        break;
                                                }
                                            }
                                        }

                                        if (curState.getTiecard_increase_fail_time()
                                                        != tmp_incre_fail_time
                                                || curState.getTiecard_increase_success_time()
                                                        != tmp_incre_sucs_time
                                                || curState.getTiecard_amount_expired_time()
                                                        != tmp_incre_exp_time) {
                                            curState.tiecard_increase_fail_time =
                                                    tmp_incre_fail_time;
                                            curState.tiecard_increase_success_time =
                                                    tmp_incre_sucs_time;
                                            curState.tiecard_amount_expired_time =
                                                    tmp_incre_exp_time;

                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("uid", uid);
                                            jsonObject.put(
                                                    "tiecard_increase_fail_time",
                                                    (tmp_incre_fail_time == 0
                                                            ? null
                                                            : tmp_incre_fail_time));
                                            jsonObject.put(
                                                    "tiecard_increase_success_time",
                                                    (tmp_incre_sucs_time == 0
                                                            ? null
                                                            : tmp_incre_sucs_time));
                                            jsonObject.put(
                                                    "tiecard_amount_expired_time",
                                                    (tmp_incre_exp_time == 0
                                                            ? null
                                                            : tmp_incre_exp_time));

                                            out.collect(jsonObject.toString());
                                            tagTieCardAmountRecordVstate.update(curState);
                                        }
                                    }
                                });

        return out;
    }

    public int getTiecard_increase_success_time() {
        return tiecard_increase_success_time;
    }

    public int getTiecard_increase_fail_time() {
        return tiecard_increase_fail_time;
    }

    public int getTiecard_amount_expired_time() {
        return tiecard_amount_expired_time;
    }
}
